package com.wenjunwu.blog.common;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Component;

import com.wenjunwu.blog.dao.SystemTokenDao;
import com.wenjunwu.blog.entity.SystemToken;

@Component
public class CustPersistentTokenRepository implements PersistentTokenRepository {

	@Autowired
	private SystemTokenDao systemTokenDao;

	@Override
	public void createNewToken(PersistentRememberMeToken token) {
		SystemToken systemToken = new SystemToken();
		systemToken.setUsername(token.getUsername());
		systemToken.setSeries(token.getSeries());
		systemToken.setToken(token.getTokenValue());
		systemToken.setLastUsed(token.getDate());
		systemTokenDao.insert(systemToken);
	}

	@Override
	public void updateToken(String series, String tokenValue, Date lastUsed) {
		SystemToken systemToken = systemTokenDao.selectByPrimaryKey(series);
		systemToken.setToken(tokenValue);
		systemToken.setLastUsed(lastUsed);
		systemTokenDao.updateByPrimaryKey(systemToken);
	}

	@Override
	public PersistentRememberMeToken getTokenForSeries(String seriesId) {
		try {
			SystemToken systemToken = systemTokenDao.selectByPrimaryKey(seriesId);
			return new PersistentRememberMeToken(systemToken.getUsername(), systemToken.getSeries(),
					systemToken.getToken(), systemToken.getLastUsed());
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void removeUserTokens(String username) {
		systemTokenDao.deleteByUsername(username);
	}
}
